package com.cgtong.android.fragment;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.activity.ActivitiesDetailActivity;
import com.cgtong.android.activity.LoginActivity;
import com.cgtong.android.activity.NewsInfoActivity;
import com.cgtong.android.activity.ReportProblemActivity;
import com.cgtong.android.activity.WebViewActivity;
import com.cgtong.android.activity.WonderfulActivitiesActivity;
import com.cgtong.android.adapter.ActivitiesAdapter;
import com.cgtong.android.adapter.NewsRecyclerAdapter;
import com.cgtong.android.base.BaseTitleFragment;
import com.cgtong.android.bean.ActivityBean;
import com.cgtong.android.bean.BannerBean;
import com.cgtong.android.bean.NewsBean;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.HomeContract;
import com.cgtong.android.mvp.presenter.HomePresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.GlideApp;
import com.cgtong.android.widget.RecyclerViewDivider;
import com.kingja.loadsir.callback.SuccessCallback;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 首页Fragment
 * Created by Sky.Bing on 2017/10/17.
 */
public class HomeFragment extends BaseTitleFragment implements HomeContract.View {


    @BindView(R.id.iv_adbanner)
    public Banner mIvAdBanner;
    @BindView(R.id.btn_problemreport)
    public Button mBtnProblemReport;
    @BindView(R.id.recycler_activities)
    public RecyclerView mActivitiesView;
    @BindView(R.id.recycler_news)
    public RecyclerView mNewsRecycler;
    @BindView(R.id.refresh_layout)
    public SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_activities_layout)
    public LinearLayout mRecyclerActivitiesLayout;

//    private BDLocation mBDLocation;
//    private LocationService mLocationService;
    private HomePresenter mHomePresenter;
    List<String> mBannerImageUrls;
    List<String> mBannerLinkUrls;
//    private LocationManager mLocationManager;
    private final int GPS_REQUEST_CODE = 0x02;

    @Override
    protected String getContentTitle() {
        return null;
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initData() {
        mBannerImageUrls = new ArrayList<>();
        mBannerLinkUrls = new ArrayList<>();
        mHomePresenter = new HomePresenter(this);
        mTitleCenterTxt.setText(getString(R.string.txt_title_main));
//        mTitleCenterTxt.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getActivity(), R.drawable.ic_home_top_arrow), null);
//        mTitleCenterTxt.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.drawable_padding_arrow_down));

//        mTitleRightTxt.setVisibility(View.VISIBLE);
//        mTitleRightTxt.setBackgroundDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_home_location));
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mTitleRightTxt.getLayoutParams();
        layoutParams.width = (int) getResources().getDimension(R.dimen.width_home_top_location);
        layoutParams.height = (int) getResources().getDimension(R.dimen.height_home_top_location);
        layoutParams.rightMargin = (int) getResources().getDimension(R.dimen.margin_right_home_top_location);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        mTitleRightTxt.setLayoutParams(layoutParams);
        mTitleRightTxt.setOnClickListener(startLbsListener);

        initRefreshLayoutAndAdapter();

//        mLocationService = ((App) getContext().getApplicationContext()).getLocationService();
//        mLocationService.registerListener(mListener);
//        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
//        mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        //设置显示轮播图片区域尺寸比例
        ConstraintLayout.LayoutParams bannerLp = (ConstraintLayout.LayoutParams) mIvAdBanner.getLayoutParams();
        float width = ScreenUtils.getScreenWidth();
        bannerLp.width = (int)width;
        bannerLp.height = (int)(width / 2.5);
        mIvAdBanner.setLayoutParams(bannerLp);
        doLocationByPermission();
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);

    }

    private void initRefreshLayoutAndAdapter() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHomePresenter.getActivities();
                mHomePresenter.getBannerList();
            }
        });
        mRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mActivitiesView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        mNewsRecycler.setNestedScrollingEnabled(false);
        mNewsRecycler.setLayoutManager(new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
    }

    @Override
    public void onDestroyView() {
//        if (null != mLocationService) {
//            mLocationService.unregisterListener(mListener); //注销掉监听
//            mLocationService.stop(); //停止定位服务
//        }
        super.onDestroyView();
    }

    private void doLocationByPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            RxPermissions rxPermissions = new RxPermissions(getActivity());
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE)
                    .subscribe(new Observer<Boolean>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (aBoolean) {
//                                initGPS();
                            } else {
                                ToastUtils.showLong(R.string.permission_request_denied);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
//            initGPS();
        }
    }

//    private void refreshLocation() {
//        mLocationService.start();
//        showStartLocation();
//    }

//    private void showStartLocation() {
//        mTitleCenterTxt.setText(getResources().getString(R.string.title_show_startlocation));
//    }

    /**
     * 定位结果回调
     */
//    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
//
//        @Override
//        public void onReceiveLocation(BDLocation location) {
//            LogUtils.d("BDLocation success:" + location.getLatitude() + ";;" + location.getLongitude());
////            EventBus.getDefault().post(location, ConstantManager.LOCATION_TAG);
//            mTitleRightTxt.setEnabled(true);
//            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
//                mBDLocation = location;
//                StringBuffer address = new StringBuffer(200);
//                if (!TextUtils.isEmpty(location.getDistrict()) && !"null".equals(location.getDistrict()))
//                    address.append(location.getDistrict());
//                if (!TextUtils.isEmpty(location.getStreet()) && !"null".equals(location.getStreet()))
//                    address.append(location.getStreet());
//                if (!TextUtils.isEmpty(address.toString()))
//                    mTitleCenterTxt.setText(address.toString());
//                else
//                    mTitleCenterTxt.setText(getResources().getString(R.string.title_location_error));
//            } else {
//                mTitleCenterTxt.setText(getResources().getString(R.string.title_location_error));
//            }
//            mLocationService.stop();
//        }
//    };

    @Override
    protected void loadDataByNet() {
        mHomePresenter.getBannerList();
        mHomePresenter.getActivities();
    }

    @Override
    protected void onDataReloadByNet(View v) {
    }

    /**
     * 启动定位服务
     */
    private View.OnClickListener startLbsListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTitleRightTxt.setEnabled(false);
            doLocationByPermission();
        }
    };

    @OnClick(R.id.btn_problemreport)
    public void onViewClicked() {
        if (((App) getContext().getApplicationContext()).isUserLogin()) {
            doReportProblemByPermission();
        } else {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
        }
    }

    private void doReportProblemByPermission() {
        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            startActivity(new Intent(getActivity(), ReportProblemActivity.class));
                        } else {
                            ToastUtils.showLong(R.string.permission_request_denied);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @OnClick(R.id.tv_activity_more)
    public void startMoreActivity() {
        Intent intent = new Intent(getActivity(), WonderfulActivitiesActivity.class);
        getActivity().startActivity(intent);
    }

    @Override
    public void showActivities(List<ActivityBean> activityBeanList) {
        if(null == mRecyclerActivitiesLayout) return;
        if (activityBeanList.size() > 0) {
            mRecyclerActivitiesLayout.setVisibility(View.VISIBLE);
            mActivitiesView.setAdapter(new ActivitiesAdapter(getContext(), activityBeanList, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivitiesDetailActivity.actionStart(getActivity(), (int) v.getTag());
                }
            }));
        } else {
            mRecyclerActivitiesLayout.setVisibility(View.GONE);
        }
        mHomePresenter.getHotNews();
    }

    @Override
    public void showHotNews(List<NewsBean> newsBeanList) {
        if (null != mNewsRecycler) {
            mNewsRecycler.setAdapter(new NewsRecyclerAdapter(getContext(), newsBeanList, new NewsRecyclerAdapter.ItemClickListener() {
                @Override
                public void onItemClick(View v, NewsBean newsBean) {
                    NewsInfoActivity.actionStart(getActivity(), newsBean.getId());
                }
            }));
            mNewsRecycler.addItemDecoration(new RecyclerViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, R.drawable.bg_divider_recyclerview));
            mRefreshLayout.setRefreshing(false);
        }
//        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
    }

    @Override
    public void showActivitiesError() {
        if(null == mRecyclerActivitiesLayout) return;
        mRecyclerActivitiesLayout.setVisibility(View.GONE);
        mHomePresenter.getHotNews();
    }

    @Override
    public void showHotNewsError() {
        if(null == mRefreshLayout) return;
        mRefreshLayout.setRefreshing(false);
//        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
    }

    @Override
    public void showBanner(List<BannerBean> bannerBeanList) {
        if (null != mIvAdBanner) {
            mIvAdBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    GlideApp.with(context).load(path).placeholder(R.drawable.icon_default_banner_loading).error(R.drawable.icon_default_banner_error).into(imageView);
                }
            });
            if (null != mBannerImageUrls)
                mBannerImageUrls.clear();
            if (null != mBannerLinkUrls)
                mBannerLinkUrls.clear();
            for (int i = 0; i < bannerBeanList.size(); i++) {
                if (i < ConstantManager.HOME_MAX_BANNER_LIST) {
                    BannerBean bannerBean = bannerBeanList.get(i);
                    mBannerImageUrls.add(bannerBean.getImageUrl());
                    mBannerLinkUrls.add(bannerBean.getLink());
                }
            }
            mIvAdBanner.setImages(mBannerImageUrls);
            mIvAdBanner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    String linkUrl = mBannerLinkUrls.get(position);
                    if(!TextUtils.isEmpty(linkUrl)){
                        WebViewActivity.actionStart(getActivity(), linkUrl);
                    }
                }
            });
            mIvAdBanner.start();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注册对象
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        // 注销
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (null != mIvAdBanner) {
            if (null != mBannerImageUrls && mBannerImageUrls.size() > 0) {
                mIvAdBanner.start();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (null != mIvAdBanner) {
            mIvAdBanner.stopAutoPlay();
        }
    }

//    private void initGPS() {
//        //判断GPS模块是否开启，如果没有则开启
//        if (!mLocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
//            final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
//            dialog.setTitle("提示");
//            dialog.setMessage("为了定位更加准确，请先打开GPS");
//            dialog.setPositiveButton("设置", new android.content.DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface arg0, int arg1) {
//                    // 转到手机设置界面，用户设置GPS
//                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                    startActivityForResult(intent, GPS_REQUEST_CODE); // 设置完成后返回到原来的界面
//                }
//            });
//            dialog.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface arg0, int arg1) {
//                    arg0.dismiss();
//                    ToastUtils.showShort("GPS未打开，将使用网络进行定位");
//                    refreshLocation();
//                }
//            });
//            dialog.show();
//        } else {
//            refreshLocation();
//        }
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == GPS_REQUEST_CODE) {
//            if (mLocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
//                refreshLocation();
//            } else {
//                ToastUtils.showShort("GPS未打开，将使用网络进行定位");
//                refreshLocation();
//            }
//        }
    }
}